package com.lapelife.backend.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lapelife.backend.common.ErrorCode;
import com.lapelife.backend.common.ResponseResult;
import com.lapelife.backend.mapper.SysMenuMapper;
import com.lapelife.backend.mapper.SysRoleMapper;
import com.lapelife.backend.model.domain.SysMenu;
import com.lapelife.backend.model.domain.SysRole;
import com.lapelife.backend.model.request.AuthenticateRequest;
import com.lapelife.backend.model.request.MenuRequest;
import com.lapelife.backend.model.request.PageRequest;
import com.lapelife.backend.model.request.RoleRequest;
import com.lapelife.backend.model.view.MenuView;
import com.lapelife.backend.model.view.RoleView;
import com.lapelife.backend.service.AuthenticateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class AuthenticateServiceImpl implements AuthenticateService {
    private SysMenuMapper sysMenuMapper;
    private SysRoleMapper sysRoleMapper;

    @Autowired
    public void setSysMenuMapper(SysMenuMapper sysMenuMapper) {
        this.sysMenuMapper = sysMenuMapper;
    }

    @Autowired
    public void setSysRoleMapper(SysRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
    }

    @Override
    public ResponseResult<String> addRoleToUser(AuthenticateRequest authenticateRequest) {
        List<Long> roleIdList = authenticateRequest.getRoleIdList();
        List<Long> userIdList = authenticateRequest.getUserIdList();
        if (roleIdList == null || userIdList == null || roleIdList.size() == 0 || userIdList.size() == 0) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        int result = 0;
        try {
            for (Long id : userIdList) {
                result += sysRoleMapper.addRoleToUser(roleIdList, id) > 0 ? 1 : 0;
            }
        } catch (Exception e) {
            return ResponseResult.fail(5521, "添加失败，该用户已存在角色");
        }
        return ResponseResult.suc("成功添加角色，数量为：" + result);
    }

    @Override
    public ResponseResult<String> addRole(RoleRequest roleRequest) {
        if (!StringUtils.hasText(roleRequest.getRoleName()) || !StringUtils.hasText(roleRequest.getRoleKey())) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        roleRequest.patternEmpty();
        SysRole sysRole = Convert.convert(SysRole.class, roleRequest);
        Integer count = sysRoleMapper.selectRoleCount(roleRequest.getRoleName(), roleRequest.getRoleKey());
        if (count > 0) {
            return ResponseResult.fail(5530, "该角色已存在");
        }
        int result = sysRoleMapper.insert(sysRole);
        if (result == 0) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        return ResponseResult.suc("角色添加成功");
    }

    @Override
    public ResponseResult<String> removeRole(RoleRequest roleRequest) {
        Long roleId = roleRequest.getRoleId();
        if (roleId == null) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        Integer count = sysRoleMapper.selectHasRoleUserCount(roleId);
        if (count > 0) {
            return ResponseResult.fail(5550, "角色删除失败，角色被关联");
        }
        int result = sysRoleMapper.deleteById(roleId);
        if (result == 0) {
            return ResponseResult.fail(ErrorCode.SYSTEM_ERROR);
        }
        return ResponseResult.suc("角色删除成功");
    }

    @Override
    public ResponseResult<String> updateRole(RoleRequest roleRequest) {
        if (roleRequest.getUserId() == null) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        roleRequest.patternEmpty();
        SysRole sysRole = Convert.convert(SysRole.class, roleRequest);
        int result = sysRoleMapper.updateById(sysRole);
        if (result == 0) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        return ResponseResult.suc("角色信息修改成功");
    }

    @Override
    public ResponseResult<Page<MenuView>> getMenu(MenuRequest menuRequest) {
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        menuRequest.patternEmpty();
        // 通过id查询 menuId
        if (menuRequest.getMenuId() != null) {
            wrapper.eq(SysMenu::getMenuId, menuRequest.getMenuId());
        }
        // 通过权限名称模糊查询 menuName
        if (menuRequest.getMenuName() != null) {
            wrapper.like(SysMenu::getMenuName, menuRequest.getMenuName());
        }
        // 通过权限字符查询 perms
        if (menuRequest.getPerms() != null) {
            wrapper.eq(SysMenu::getPerms, menuRequest.getPerms());
        }
        // 通过状态查询 status
        if (menuRequest.getStatus() != null) {
            wrapper.eq(SysMenu::getStatus, menuRequest.getStatus());
        }
        // 通过是否显示查询 visible
        if (menuRequest.getVisible() != null) {
            wrapper.eq(SysMenu::getVisible, menuRequest.getVisible());
        }
        // 进行分页
        Page<SysMenu> sysMenuPage = new Page<>(menuRequest.getCurrent(), menuRequest.getSize());
        sysMenuPage.setOrders(Arrays.asList(new OrderItem("menu_name", true), new OrderItem("menu_id", true)));
        sysMenuMapper.selectPage(sysMenuPage, wrapper);
        // 取出分页数据
        List<MenuView> list = Convert.toList(MenuView.class, sysMenuPage.getRecords());
        Page<MenuView> menuViewPage = new Page<>(sysMenuPage.getCurrent(), sysMenuPage.getSize());
        menuViewPage.setTotal(sysMenuPage.getTotal());
        menuViewPage.setPages(sysMenuPage.getPages());
        menuViewPage.setRecords(list);
        return ResponseResult.suc(menuViewPage);
    }

    @Override
    public ResponseResult<String> addMenuToRole(AuthenticateRequest authenticateRequest) {
        List<Long> roleIdList = authenticateRequest.getRoleIdList();
        List<Long> menuIdList = authenticateRequest.getMenuIdList();
        if (menuIdList == null || roleIdList == null || menuIdList.isEmpty() || roleIdList.isEmpty()) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        int result = 0;
        try {
            for (Long id : roleIdList) {
                result += sysMenuMapper.addMenuToRole(menuIdList, id) > 0 ? 1 : 0;
            }
        } catch (Exception e) {
            return ResponseResult.fail(5521, "添加失败，角色已存在权限");
        }
        return ResponseResult.suc("成功添加权限，添加数量为" + result);
    }

    @Override
    public ResponseResult<String> deleteRoleById(Long id) {
        if (id == null) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        Integer relation = sysRoleMapper.countRoleRelation(id);
        if (relation > 0) {
            return ResponseResult.fail(ErrorCode.RESULT_ERROR.getCode(), "删除失败，有用户或权限与该角色存在关联");
        }
        int result = sysRoleMapper.deleteById(id);
        if (result > 0) {
            return ResponseResult.suc("删除成功");
        }
        return ResponseResult.fail(ErrorCode.RESULT_ERROR.getCode(), "该角色不存在");
    }

    @Override
    public ResponseResult<String> deleteRoleFor(AuthenticateRequest authenticateRequest) {
        List<Long> roleIdList = authenticateRequest.getRoleIdList();
        Long userId = authenticateRequest.getUserId();
        if (userId == null) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        if (roleIdList == null || roleIdList.size() == 0) {
            return ResponseResult.suc("删除成功");
        }
        Integer result = sysRoleMapper.deleteRoleFor(userId, roleIdList);
        return ResponseResult.suc("删除成功，删除角色数量：" + result);
    }

    @Override
    public ResponseResult<String> deleteMenuFor(AuthenticateRequest authenticateRequest) {
        Long roleId = authenticateRequest.getRoleId();
        List<Long> menuIdList = authenticateRequest.getMenuIdList();
        if (menuIdList == null || roleId == null || menuIdList.isEmpty()) {
            return ResponseResult.fail(ErrorCode.PARAMS_ERROR);
        }
        Integer result = sysMenuMapper.deleteMenuFor(roleId, menuIdList);
        return ResponseResult.suc("删除成功，成功删除的权限数量为：" + result);
    }


    @Override
    public ResponseResult<Page<RoleView>> getRole(RoleRequest roleRequest) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        roleRequest.patternEmpty();
        // 通过id查询 roleId
        if (roleRequest.getRoleId() != null) {
            wrapper.eq(SysRole::getRoleId, roleRequest.getRoleId());
        }
        // 通过角色名模糊查询 roleName
        if (roleRequest.getRoleName() != null) {
            wrapper.like(SysRole::getRoleName, roleRequest.getRoleName());
        }
        // 通过角色关键词查询 roleKey
        if (roleRequest.getRoleKey() != null) {
            wrapper.eq(SysRole::getRoleKey, roleRequest.getRoleKey());
        }
        // 通过角色状态查询 status
        if (roleRequest.getStatus() != null) {
            wrapper.eq(SysRole::getStatus, roleRequest.getStatus());
        }
        // 进行分页
        Page<SysRole> sysRolePage = new Page<>(roleRequest.getCurrent(), roleRequest.getSize());
        sysRolePage.setOrders(Arrays.asList(new OrderItem("role_name", true), new OrderItem("role_id", true)));
        sysRoleMapper.selectPage(sysRolePage, wrapper);
        // 取出分页数据
        List<RoleView> list = Convert.toList(RoleView.class, sysRolePage.getRecords());
        Page<RoleView> roleViwePage = new Page<>(sysRolePage.getCurrent(), sysRolePage.getSize());
        roleViwePage.setTotal(sysRolePage.getTotal());
        roleViwePage.setPages(sysRolePage.getPages());
        roleViwePage.setRecords(list);
        return ResponseResult.suc(roleViwePage);
    }
}
